import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDao {

    public void register(Student student) throws SQLException {
        String sql = "INSERT INTO student (account, password, name) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, student.getAccount());
            ps.setString(2, student.getPassword());
            ps.setString(3, student.getName());
            ps.executeUpdate();
        }
    }


    public Student login(String account, String password) throws SQLException {
        String sql = "SELECT * FROM student WHERE account = ? AND password = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, account);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                Student student = new Student();
                student.setId(rs.getInt("id"));
                student.setAccount(rs.getString("account"));
                student.setName(rs.getString("name"));
                return student;
            }
            return null;
        }
    }


    public void updatePassword(String account, String newPassword) throws SQLException {
        String sql = "UPDATE student SET password = ? WHERE account = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, newPassword); // 新密码
            ps.setString(2, account);     // 账号（唯一标识）
            ps.executeUpdate();
        }
    }
}